package main

import (
	"block/core"
	"encoding/json"
	"io"
	"net/http"
)

var blockChain *core.BlockChain

func run() {
	http.HandleFunc("/blockChain/get", blockChainGetHandler)
	http.HandleFunc("/blockChain/write", blockChainWriteHandler)
	http.ListenAndServe("localhost:8899", nil)
}

func blockChainGetHandler(w http.ResponseWriter, r *http.Request) {
	bytes, error := json.MarshalIndent(blockChain.Blocks, "", "")

	if error != nil {
		http.Error(w, error.Error(), http.StatusInternalServerError)
		return
	}
	io.WriteString(w, string(bytes))
}

func blockChainWriteHandler(w http.ResponseWriter, r *http.Request) {
	data := r.URL.Query().Get("data")
	blockChain.SendBlock(data)
	blockChainGetHandler(w, r)
}

func main() {
	go func() {
		blockChain = core.CreateBlockChain()
	}()

	run()
}
